package com.wecommodule.bpm.ext.framework.config;

import com.wecommodule.bpm.ext.framework.config.support.HttpConfigProperties;
import com.wecommodule.bpm.ext.framework.config.support.OkHttpConfigSupport;
import okhttp3.ConnectionSpec;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * OkHttp 配置
 *
 */
@Configuration
public class OkHttpClientConfig extends OkHttpConfigSupport {
    @Bean("bpmOkHttpClient")
    @NotNull
    public OkHttpClient activityOkHttpClient(@NotNull @Value("${restTemplateCallConfig.bpm.callTimeoutMS}") Long callTimeoutMS,
                                             @NotNull @Value("${restTemplateCallConfig.bpm.maxIdle}") Integer maxIdle,
                                             @NotNull @Value("${restTemplateCallConfig.bpm.keepAliveSeconds}") Long keepAliveSeconds,
                                             @NotNull @Value("${restTemplateCallConfig.bpm.readTimeoutMS}") Long readTimeoutMS,
                                             @NotNull @Value("${restTemplateCallConfig.bpm.writeTimeoutMS}") Long writeTimeoutMS,
                                             @NotNull @Value("${restTemplateCallConfig.bpm.connectionMS}") Long connectionMS,
                                             @NotNull @Value("${restTemplateCallConfig.bpm.toService}") String toService){
        HttpConfigProperties configProperties = new HttpConfigProperties();
        configProperties.setCallTimeoutMS(callTimeoutMS);
        configProperties.setMaxIdle(maxIdle);
        configProperties.setKeepAliveSeconds(keepAliveSeconds);
        configProperties.setReadTimeoutMS(readTimeoutMS);
        configProperties.setWriteTimeoutMS(writeTimeoutMS);
        configProperties.setConnectTimeoutMS(connectionMS);
        configProperties.setToService(toService);

        // 日志拦截器
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        List<ConnectionSpec> connectionSpecs = Arrays.asList(ConnectionSpec.CLEARTEXT, ConnectionSpec.MODERN_TLS);
        OkHttpClient.Builder builder = defaultBuilder(connectionSpecs, configProperties, true,
                new Interceptor[]{logging});
        return builder.build();
    }


}
